layui.use(['jquery','layer','table','form'],function(){
    var $=layui.jquery;
    var layer=layui.layer;
    var table=layui.table;
    var form=layui.form;

    importJsUser=function importJsUser(){
        layer.open({
            type:2,
            title:"上传文件",
            area:["400px","300px"],
            btn:["确定","取消"],
            offset: 'auto',
            content:"import-jsUser.html",
            end:function(){
                getTable()
            }
        })
    }

    addJsUser=function addJsUser(){
        parent.addTab(87);
    }

    getDepts();

    //查询所有部门
    function getDepts() {
        var setting = {
            data: {
                simpleData: {
                    enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
                    idKey: "id",  //节点数据中保存唯一标识的属性名称
                    pIdKey: "parentId",    //节点数据中保存其父节点唯一标识的属性名称
                    rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
                },
                key: {
                    name: "deptName"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
                }
            },
            view: {
                dblClickExpand: false
            },
            check: {
                enable : false,  //true 、 false 分别表示 显示 、不显示 复选框或单选框
                nocheckInherit:true  //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
            },
            callback: {
                onClick: zTreeOnClick,//点击树节点展示对应table信息
                onRightClick: OnRightClick
            }
        };

        $.ajax({
            url: '/login/getJsDept',
            dataType: 'json',
            success: function (data) {
                //部门树的渲染
                zTree = $.fn.zTree.init($("#demoTree"), setting, data.data);//初始化树
                zTree.expandAll(true);    //true 节点全部展开、false节点收缩
            }
        });

        rMenu = $("#rMenu");

        //点击节点
        function zTreeOnClick() {
            var nodes = zTree.getSelectedNodes();
            var node = nodes[0];
            if(!node.isParent){
                $.ajax({
                    url:"/login/getJsUserById",
                    data:{'id':node.id},
                    dataType:"json",
                    success:function (data) {
                        demoTable(data.data);
                    }
                })
            }else{
                layer.msg("请选择最小分类类别");
            }
        }
        //树的一系列配置
        function OnRightClick(event, treeId, treeNode) {
            if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
                zTree.cancelSelectedNode();
                showRMenu("root", event.clientX, event.clientY);
            } else if (treeNode && !treeNode.noR) {
                zTree.selectNode(treeNode);
                showRMenu("node", event.clientX, event.clientY);
            }
        }
        function showRMenu(type, x, y) {
            $("#rMenu ul").show();
            if (type=="root") {
                $("#m_del").hide();
            } else {
                $("#m_del").show();
            }

            y += document.body.scrollTop;
            x += document.body.scrollLeft;
            rMenu.css({'position':'fixed',"top":y+"px", "left":x+"px", "visibility":"visible"});

            $("body").bind("mousedown", onBodyMouseDown);
        }
        function hideRMenu() {
            if (rMenu) rMenu.css({"visibility": "hidden"});
            $("body").unbind("mousedown", onBodyMouseDown);
        }
        function onBodyMouseDown(event){
            if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length>0)) {
                rMenu.css({"visibility" : "hidden"});
            }
        }

        //点击编辑部门后弹出弹出层
        updateZtreeNode = function updateZtreeNode() {
            var nodes = zTree.getSelectedNodes();
            var node = nodes[0];
            if(node.id == 0 || node.id == 1 || node.id == 2 || node.id == 3 || node.id == 4){
                layer.msg('此部门不可以被修改');
                return;
            }
            layer.prompt({
                title: '修改部门名称',
                value: node.deptName,
                area: ['300px', '100px']
            }, function(value, index, elem){
                $.ajax({
                    url:"/login/updateJsDeptNameById",
                    data:{'id':node.id,'deptName':value},
                    type:"post",
                    dataType:"json",
                    success:function (data) {
                        getDepts();
                    }
                })
                layer.close(index)
            });
        }

        //点击删除部门后弹出弹出层
        removeZtreeNode = function removeZtreeNode() {
            var nodes = zTree.getSelectedNodes();
            var node = nodes[0];
            if(node.id == 0 || node.id == 1 || node.id == 2 || node.id == 3 || node.id == 4){
                layer.msg('此部门不可以被修改');
                return;
            }
            var layerIndex = layer.confirm('确定要删除"' + node.deptName + '"么?', {
                btn: ['确定','取消']
            }, function(){
                $.ajax({
                    url:"/login/deleteJsDeptById",
                    data:{'id':node.id},
                    type:"post",
                    dataType:"json",
                    success:function (data) {
                        getDepts();
                    }
                })
                layer.close(layerIndex);
            }, function(){
                layer.close(layerIndex);
            });
        }

    }

    refresh=function refresh(){
        location.reload();
    }

    retrieval=function retrieval(){
        layer.open({
            type : 2,
            title : "高级检索",
            area : [ '900px', '500px' ],
            shade : 0,
            offset: 'auto',
            content :"senior-sample.html",
            btn:['确定','取消'],
            yes: function(index, layero){
                var child = layero.find('iframe').contents();
                var account= child.find("input[name=account]").val();
                var trueName=child.find("input[name=trueName]").val();
                var deptName=child.find("input[name=deptName]").val();
                var registerDate=child.find("input[name=registerDate]").val();
                var param = {
                    'account':account,
                    'trueName':trueName,
                    'deptName':deptName,
                    'registerDate':registerDate,
                }
                $.ajax({
                    url:"/login/getUserListRetrieval",
                    data:param,
                    dataType:"json",
                    success:function (data) {
                        demoTable(data.data);
                        layer.close(layer.index);
                    }
                })
            }
        })
    }

    search=function search(){
        var account=$("input[name=account]").val();
        var trueName=$("input[name=trueName]").val();
        var deptName=$("input[name=deptName]").val();
        var registerDate=$("input[name=registerDate]").val();
        getTable(account,trueName,deptName,registerDate);
    }

    getTable();

    function getTable(account,trueName,deptName,registerDate){
        $.ajax({
            url:"/login/getUserList",
            dataType:"json",
            data:{'account':account,'trueName':trueName,'deptName':deptName,'registerDate':registerDate},
            success:function (data) {
                demoTable(data.data);
            }
        })
    }

    function demoTable(data) {
        table.render({
            elem: '#demoTable',
            title: "后台人员列表",
            data: data,
            toolbar: '#tableHeader',
            limit: 10,
            page: {
                layout: ['count', 'prev', 'page', 'next', 'limit', 'skip', 'refresh'],
                limits: [10, 20, 30],
                first: "首页",
                last: "尾页",
            },
            cols: [[
                {type: 'checkbox'},
                {title: '序号',align:'center', templet: function (data) {
                        return data.LAY_INDEX;
                    }},
                {field: "trueName", title: "用户姓名", align: 'center'},
                {field: "acatarUrl", title: "用户头像", align: 'center',width:130,templet:function(data){
                        return '<img src="'+data.acatarUrl+'"';
                    }},
                {field: "sex", title: "性别", align: 'center'},
                {field: "account", title: "用户账号", align: 'center'},
                {field: "deptName", title: "所属部门", align: 'center'},
                {field: "enabled", title: "是否启用", align: 'center',templet:function(data){
                        if(data.enabled==1){
                            return '<input type=\"checkbox\" value="'+data.userId+'" lay-skin=\"switch\" lay-text=\"启用|禁用"\ checked lay-filter="switchTest">';
                        }else if(data.enabled==2){
                            return '<input type=\"checkbox\" value="'+data.userId+'" lay-skin=\"switch\" lay-text=\"启用|禁用" lay-filter="switchTest"\>';
                        }
                    }},
                {field: "status", title: "账号状态", align: 'center',templet:function(data){
                        if(data.status==1){
                            return '<input type=\"checkbox\" value="'+data.userId+'" lay-skin=\"switch\" lay-text=\"使用中|封停中"\ checked lay-filter="switchTestTwo">';
                        }else if(data.status==4){
                            return '<input type=\"checkbox\" value="'+data.userId+'" lay-skin=\"switch\" lay-text=\"使用中|封停中" lay-filter="switchTestTwo"\>';
                        }else{
                            return '<input type=\"checkbox\" value="'+data.userId+'" lay-skin=\"switch\" lay-text=\"使用中|封停中" lay-filter="switchTestTwo"\>';
                        }
                    }},
                {field: "registerDate", title: "注册时间", align: 'center'},
                {field: '', title: "操作", align: 'center', toolbar: '#button_caozuo'}
            ]]
        })
    }

    form.on('switch(switchTest)', function(data){
        if(data.elem.checked==true){
            $.ajax({
                url:"/login/updateJsUserEnabled",
                type:"post",
                dataType:"json",
                data:{'enabled':1,'userId':data.value},
                success:function (data) {
                    getTable();
                    layer.msg("修改成功！！！");
                }
            })
        }else{
            $.ajax({
                url:"/login/updateJsUserEnabled",
                type:"post",
                dataType:"json",
                data:{'enabled':2,'userId':data.value},
                success:function (data) {
                    getTable();
                    layer.msg("修改成功！！！");
                }
            })
        }
    })

    form.on('switch(switchTestTwo)', function(obj){
        if(obj.elem.checked==true){
            //解封
            $.ajax({
                url:"/login/updateJsUserStatus",
                type:"post",
                dataType:"json",
                data:{'status':1,'userId':obj.value},
                success:function (data) {
                    getTable();
                    console.log(obj);
                    layer.msg("账号已解封！！！");
                }
            })
        }else{
            //封停
            $.ajax({
                url:"/login/updateJsUserStatus",
                type:"post",
                dataType:"json",
                data:{'status':4,'userId':obj.value},
                success:function (data) {
                    getTable();
                    console.log(obj);
                    layer.msg("账号已封禁！！！");
                }
            })
        }
    })

    table.on('tool(demoTable)',function (obj) {
        var event = obj.event;
        if (event == "selectTable"){
            layer.open({
                type:2,
                title:"查看",
                area:["95%","100%"],
                scrollbar: false,
                offset:'auto',
                btn:["确定","取消"],
                content:"back-stage-select.html",
                success:function(layero,index){
                    var child = layero.find('iframe').contents();
                    child.find("#account").text(obj.data.account);
                    child.find("#trueName").text(obj.data.trueName);
                    child.find("#sex").text(obj.data.sex);
                    child.find("#phone").text(obj.data.phone);
                    child.find("#idCard").text(obj.data.idCard);
                    child.find("#birthDate").text(obj.data.birthDate);
                    child.find("#registerDate").text(obj.data.registerDate);
                    child.find("#deptName").text(obj.data.deptName);
                    child.find("#email").text(obj.data.email);
                    child.find("#acatarUrl").attr("src",obj.data.acatarUrl);
                    child.find("#freestyle").text(obj.data.freestyle);
                },
                end:function (layero, index) {
                    layer.close(index);
                }
            });
        }else if (event == "powerTable") {
            localStorage.setItem("userId",obj.data.userId);
            layer.open({
                type:2,
                title:"权限",
                area:["700px","500px"],
                offset: 'auto',
                btn:["确定","取消"],
                content:"power-back-stage.html",
                success:function(layero,index){
                    var child = layero.find('iframe').contents();
                    child.find("input[name=trueName]").val(obj.data.trueName);
                    child.find("#remark").text(obj.data.remark);
                },
                yes:function(index,layero){
                    var child = layero.find('iframe').contents();
                    var checkbox=child.find("input[name=authorityId]");
                    $.ajax({
                        url:"/login/deleteJsUserPower",
                        data:{'userId':obj.data.userId},
                        type:'post',
                        dataType:'json',
                        success:function (data) {
                        }
                    })
                    for(var j=0;j<checkbox.length;j++){
                        if(checkbox[j].checked==true){
                            $.ajax({
                                url:"/login/addJsUserPower",
                                data:{'userId':obj.data.userId,'authorityId':checkbox[j].value,'type':2},
                                type:'post',
                                dataType:'json',
                                success:function (data) {
                                    layer.close(index);
                                    getTable();
                                }
                            })
                        }
                    }
                }
            })
        }else if (event == "updateTable") {
            layer.open({
                type:2,
                title:"修改",
                area:["1000px","700px"],
                offset: 'auto',
                content:"update-back-stage.html",
                success:function(layero,index){
                    var child = layero.find('iframe').contents();
                    child.find("#userHeadPortrait").attr("src",obj.data.acatarUrl);
                    child.find("input[name=acatarUrl]").val(obj.data.acatarUrl);
                    child.find("input[name=account]").val(obj.data.account);
                    child.find("input[name=trueName]").val(obj.data.trueName);
                    child.find("input[name=sex]").val(obj.data.sex);
                    child.find("input[name=idCard]").val(obj.data.idCard);
                    child.find("input[name=birthDate]").val(obj.data.birthDate);
                    child.find("input[name=deptName]").val(obj.data.deptName);
                    child.find("input[name=registerDate]").val(obj.data.registerDate);
                    child.find("input[name=registerIp]").val(obj.data.registerIp);
                    child.find("input[name=email]").val(obj.data.email);
                    child.find("#freestyle").text(obj.data.freestyle);
                    child.find("#userId").val(obj.data.userId);
                },
                end: function(){
                    getTable();
                }
            })
        }else if (event == "shutdownTable") {
            var child;
            if(obj.data.status==4||obj.data.status==3||obj.data.status==2){
                layer.msg("此账号已被封停");
            }else if(obj.data.status==1){
                layer.open({
                    type:2,
                    title:"封停",
                    area:["700px","450px"],
                    offset: 'auto',
                    btn:["确定","取消"],
                    content:"shut-down-back-stage.html",
                    success:function(layero,index){
                        child = layero.find('iframe').contents();
                        child.find("input[name=account]").val(obj.data.account);
                    },
                    yes:function(index,layero){
                        $.ajax({
                            url:"/login/updateJsUserStatus",
                            data:{'status':4,'userId':obj.data.userId},
                            type:'post',
                            dataType:'json',
                            success:function (data) {
                                layer.close(index);
                                getTable();
                                layer.msg("已封停！！！");
                            }
                        })
                    },
                    end:function (layero, index) {
                        layer.close(index);
                    }
                })
            }
        }
    })


})